package cn.mulanbay.web.controller;

import cn.mulanbay.business.handler.CacheHandler;
import cn.mulanbay.business.handler.MessageHandler;
import cn.mulanbay.common.bean.DataGrid;
import cn.mulanbay.common.bean.ResultBean;
import cn.mulanbay.common.exception.ErrorCode;
import cn.mulanbay.common.exception.ValidateError;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller的基类
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
public class BaseController {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected MessageHandler messageHandler;

    @Autowired
    protected CacheHandler cacheHandler;

    private static ResultBean defaultResultBean = new ResultBean();

    private static List emptyList = new ArrayList<>();

    /**
     * 跟easyui结合
     *
     * @param pr
     * @return
     */
    protected ResultBean callbackDataGrid(Page<?> pr) {
        ResultBean rb = new ResultBean();
        DataGrid dg = new DataGrid();
        dg.setPage((int) pr.getCurrent());
        dg.setPageSize((int) pr.getSize());
        dg.setTotal(pr.getTotal());
        dg.setRows(pr.getRecords() == null ? emptyList : pr.getRecords());
        rb.setData(dg);
        return rb;
    }


    protected ResultBean callback(Object o) {
        if (o == null) {
            return defaultResultBean;
        }
        ResultBean rb = new ResultBean();
        rb.setData(o);
        return rb;
    }

    /**
     * 直接返回错误代码
     *
     * @param errorCode
     * @return
     */
    protected ResultBean callbackErrorCode(int errorCode) {
        ResultBean rb = new ResultBean();
        rb.setCode(errorCode);
        ValidateError ve = messageHandler.getErrorCodeInfo(errorCode);
        rb.setMessage(ve.getErrorInfo());
        return rb;
    }

    /**
     * 直接返回错误信息
     *
     * @param msg
     * @return
     */
    protected ResultBean callbackErrorInfo(String msg) {
        ResultBean rb = new ResultBean();
        rb.setCode(ErrorCode.DO_BUSS_ERROR);
        rb.setMessage(msg);
        return rb;
    }

}
